package com.app.micaihu.view.main.topic

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnFocusChangeListener
import android.widget.TextView
import com.android.volley.VolleyError
import com.app.base.BaseActivity
import com.app.micaihu.R
import com.app.micaihu.app.AppApplication
import com.app.micaihu.base.bean.DataBean
import com.app.micaihu.bean.infor.UploadFileResult
import com.app.micaihu.bean.topic.PostItemBean
import com.app.micaihu.bean.topic.SendImageBean
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.configure.URIContant
import com.app.micaihu.custom.components.ParamMap
import com.app.micaihu.custom.view.MaxByteLengthEditTextWithoutEmoji.OnLimitedListener
import com.app.micaihu.listener.HttpListener
import com.app.micaihu.manager.AppConfigManager
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.DialogUtils
import com.app.micaihu.utils.HttpUtils
import com.app.micaihu.utils.OkHttp3Helper
import com.app.micaihu.utils.OkHttp3Helper.OnUploadResponseCallBack
import com.app.micaihu.view.main.view.GlideEngine
import com.app.micaihu.view.main.view.keybord.Control
import com.app.utils.util.GsonUtils
import com.app.utils.util.ToastUtils
import com.app.utils.util.ViewFrameUtils
import com.app.utils.util.ViewSizeUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ViewUtils
import com.google.gson.reflect.TypeToken
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.huantansheng.easyphotos.setting.Setting
import com.jeremyliao.liveeventbus.LiveEventBus
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.activity_sendpost.*
import kotlinx.android.synthetic.main.include_sendcircle_bottom.*
import okhttp3.Response
import java.io.File
import java.util.*

/**
 * 发表文章页面
 *
 * @author linkai
 */
class PostSendActivity : BaseActivity(), View.OnClickListener, OnFocusChangeListener, TextWatcher {
    companion object {
        private const val PHOTO_CODE = 101 // 请求相机的请求码
        private const val MAX_CHAR = 4000
        private const val MIN_CHAR = 60
    }

    private var confirmDialog: View? = null
    private var dialogParams: HashMap<String, Any>? = null
    private var images: MutableList<SendImageBean> = ArrayList() // 选中的图片集合
    private var netPicList: MutableList<String?> = ArrayList() //上传的文件网络连接集合
    private val urlMap: HashMap<Int, String> = HashMap() //存储url的map
    private var isSendSucces = false //默认false  代表默认没有发帖 = false
    private var mSendPostContent: String? = null//发表的内容
    private val maxNumPic = 9 //最多显示的图片数量
    private val mSp: SharedPreferences by lazy {
        AppConfigManager.getInstance().configSP
    }
    private var tansImg = TypeConstant.TANS_IMG //默认显示可发图片
    private var isShaidan = false
    private val topicId = "0"
    private var gid = ""
    private val RETURN_UPDATA = 103 //返回更新数据
    private val UPLOAD_FAIL = 111 //上传失败
    private val UPLOAD_NET_FAIL = 122 //网络问题
    private val COMPRESS_FAIL = 101 //压缩失败
    private var mSendPostTitle: String? = null
    private var mControl: Control? = null
    private var answer = 0 // 1 提问
    private var isAnswer = false // 是否是 提问
    private var resultPhotos: ArrayList<Photo> = ArrayList<Photo>()

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                RETURN_UPDATA -> {
                    DialogUtils.getInstance().dismissProgressDialog()
                    changeImageGridData()
                }
                UPLOAD_FAIL -> {
                    DialogUtils.getInstance().dismissProgressDialog()
                    val index = msg.obj as Int
                    ToastUtils.showText("第" + index + "图片上传失败,请重新发表")
                }
                COMPRESS_FAIL -> ToastUtils.showText("获取图片失败,请检查图片是否存在")
                UPLOAD_NET_FAIL -> ToastUtils.showText("网络异常,请稍后再试")
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_sendpost
    }

    override fun getBundle(bundle: Bundle) {
        isShaidan = bundle.getBoolean(Config.Extra.PARAMETER1, false)
        //限制是否发帖
        val tansTemp = bundle.getString("tansImg", "")
        if (!TextUtils.isEmpty(tansTemp)) {
            tansImg = tansTemp
        }
        isAnswer = bundle.getBoolean(Config.Extra.answer)
        gid = bundle.getString(Config.Extra.id, "")
    }

    override fun setData() {
        initView()
        setAnswerData(isAnswer)
        mControl = Control(llRoot, this)
        mControl?.initContentLayout()
//        // 获取焦点 弹出键盘
        ViewUtils.runOnUiThreadDelayed({ KeyboardUtils.showSoftInput(noEmojiTitle) }, 200)

    }


    override fun addListeners() {
        switchAnswer.setOnCheckedChangeListener { buttonView, isChecked ->
            setAnswerData(isChecked)
        }
        noEmojiTitle.onFocusChangeListener = OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                if (menu2 != null) {
                    menu2.visibility = View.GONE
                }
            }
        }
        noEmojiTitle.setOnLimitedListener(object : OnLimitedListener {
            override fun onLimit(source: CharSequence, len: Int) {
                if (TextUtils.isEmpty(source) && len >= MIN_CHAR) {
                    ToastUtils.makeText(AppApplication.getInstance().getString(R.string.post_title_limit))
                }
            }

            override fun onEmojiInput() {
                ToastUtils.makeText(AppApplication.getInstance().getString(R.string.post_title_no_emoji))
            }
        })
    }


    /**
     * 初始化布局
     */
    private fun initView() {

        /****内容控件相关  start */
        content.maxByteLength = MAX_CHAR

        noEmojiTitle.maxByteLength = MIN_CHAR
        if (!TextUtils.isEmpty(mSp.getString(ConfigKeyConstant.sendArticle_content, ""))) {
            content.setText(mSp.getString(ConfigKeyConstant.sendArticle_content, ""))
        }
        if (!TextUtils.isEmpty(mSp.getString(ConfigKeyConstant.sendArticle_title, ""))) {
            noEmojiTitle.setText(mSp.getString(ConfigKeyConstant.sendArticle_title, ""))
        }
        content.setOnClickListener(this)
        content.onFocusChangeListener = this
        content.addTextChangedListener(this)
        //添加图片按钮
        menu1.setOnClickListener(this)
        //添加表情按钮
        menu2.setOnClickListener(this)
        //发帖按钮
        tv_sendpost.setOnClickListener(this)
        addPic.setOnClickListener(this)

        //更改发帖按钮的颜色
        changePostBtnColor()

        //配置表情显示的控件
        biaoqingview.configView(content, includeBottom, 5, R.drawable.expression_yuandian, thisActivity)

        //展示添加图片的gridview配置
        ViewSizeUtils.changeViewAuto720(addPic, 140, 140)
        ll_picContainer.setOnClickListener(this)


        //根据服务器给定的数据 显示/隐藏 是否可发图片
        if (TextUtils.equals(tansImg, TypeConstant.TANS_IMG)) {
            menu1.visibility = View.VISIBLE
            ivContainer.visibility = View.VISIBLE
            val imagesStr = mSp.getString(ConfigKeyConstant.sendArticle_images, "")
            if (!TextUtils.isEmpty(imagesStr)) {
                val split = imagesStr!!.split(",".toRegex()).toTypedArray()
                for (i in split.indices) {
                    val sendImageBean = SendImageBean(split[i])
                    images.add(sendImageBean)
                }
                changeImageGridData()
            }
        } else {
            menu1.visibility = View.GONE
            ivContainer.visibility = View.GONE
        }
        /******底部菜单相关  end */
    }

    private fun setAnswerData(isAnswer: Boolean) {
        this.isAnswer = isAnswer
        if (isAnswer) {
            getCommonTitle().title = AppApplication.getInstance().getString(R.string.post_send_question)
            answer = 1
            switchAnswer.isChecked = true
            noEmojiTitle.hint = "请输入你的问题"
            content.hint = "请输入你的问题描述"
        } else {
            getCommonTitle().title = AppApplication.getInstance().getString(R.string.post_send_post)
            answer = 0
            switchAnswer.isChecked = false
            noEmojiTitle.hint = "文章标题(选填)"
            content.hint = "内容"
        }
    }

    override fun onClick(v: View) {
        if (v is PicWithDel) {
            try {
                val sib = v.getTag() as SendImageBean
                ll_picContainer.removeView(v)
                if (images != null && images.size > 0) {
                    images.remove(sib)
                }
                if (images.size >= maxNumPic) {
                    addPic.visibility = View.GONE
                } else {
                    addPic.visibility = View.VISIBLE
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        when (v.id) {
            R.id.tv_ok -> DialogUtils.getInstance().dismissCDialog()
            R.id.content -> {
            }
            R.id.tv_sendpost -> sendArticle()
            R.id.menu1 -> {
                if (images != null && images.size >= maxNumPic) {
                    ToastUtils.makeText("最多支持上传" + maxNumPic + "张图片")
                    return
                }
                openPhotos()
            }
            R.id.menu2 -> if (mControl?.isEmojiLayoutShow!!) {
                if (mControl?.isSoftKeyboardShow!!) {
                    mControl?.onHideClick()
                } else {
                    KeyboardUtils.showSoftInput()
                }
            } else {
                mControl?.onShowClick()
            }
            R.id.addPic -> openPhotos()
            else -> {
            }
        }
    }

    private fun openPhotos() {
        KeyboardUtils.hideSoftInput(this)
        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority(Config.fileProvider)
                .setCount(maxNumPic - images.size)
                .setPuzzleMenu(false)
                .setCleanMenu(false)
                .setCameraLocation(Setting.LIST_FIRST)
                .start(Config.ResultCode.resultCodePhoto)
    }


    /**
     * 隐藏键盘和表情
     */
    private fun hideSoftBiaoQin() {
        //关闭键盘
        ViewFrameUtils.closeInputSoft(thisActivity, content)
        if (biaoqingview != null) {
            biaoqingview.visibility = View.GONE
        }
    }

    /**
     * 发表文章
     */
    private fun sendArticle() {
        if (netPicList != null) {
            urlMap.clear()
        }
        //判断是否登陆
        if (!UserInforManager.getInstance().isLogin) {
            UserInforManager.getInstance().toLoginPage(this)
            return
        }
        mSendPostTitle = noEmojiTitle.text.toString().trim { it <= ' ' }
        mSendPostContent = content.text.toString().trim { it <= ' ' }
        if (isAnswer) {
            if (TextUtils.isEmpty(mSendPostTitle)) {
                ToastUtils.makeText("问题不能为空")
                return
            }
        } else {
            if (TextUtils.isEmpty(mSendPostContent)) {
                ToastUtils.makeText("发表内容不能为空")
                return
            }
        }

        if (images != null && images.size > 0) {
            //如果有图片则先上传图片,图片全部上传完毕后在发布贴子
            DialogUtils.getInstance().showProgressDialog(thisActivity, "正在发表中...")
            for (i in images.indices) {
                uploadFile(images[i].file, i)
            }
        } else {
            sendToicPost() //发表贴子
        }
    }

    /**
     * 上传文件
     *
     * @param uploadFile 上传的图片
     * @param i
     */
    private fun uploadFile(uploadFile: File?, i: Int) {
        if (uploadFile == null || !uploadFile.exists()) {
            return
        }
        val paramMap: HashMap<String?, String?> = HashMap<String?, String?>()
        paramMap["type"] = TypeConstant.UPLOAD_TYPE2
        paramMap["uid"] = UserInforManager.getInstance().userInfor.uid
        paramMap["filename"] = "filename"
        paramMap["timestamp"] = System.currentTimeMillis().toString() + ""
        OkHttp3Helper.getInstance().uploadAsynFile(URIContant.UP_FILE, uploadFile, paramMap, object : OnUploadResponseCallBack() {
            override fun onStart() {
                super.onStart()
            }

            override fun onFailure() {
                super.onFailure()
                val msg = Message.obtain()
                msg.what = UPLOAD_NET_FAIL
                msg.obj = i
                handler.sendMessage(msg)
            }

            override fun onSucess(response: Response) {
                super.onSucess(response)
                try {
                    if (response != null) {
                        val json = response.body!!.string()
                        val gson = GsonUtils.getInstance().gson
                        val uploadFileResult = gson.fromJson<DataBean<UploadFileResult?>>(json, object : TypeToken<DataBean<UploadFileResult?>?>() {}.type)
                        if (uploadFileResult != null && uploadFileResult.noError() && uploadFileResult.data != null) {
                            if (netPicList == null) {
                                netPicList = ArrayList()
                            }
                            urlMap[i] = uploadFileResult.data!!.url
                            //请求发贴方法
                            sendToicPost()
                        } else {
                            val msg = Message.obtain()
                            msg.what = UPLOAD_FAIL
                            msg.obj = i
                            handler.sendMessage(msg)
                            //ToastUtils.showText("图片"+uploadFile.getAbsolutePath()+"上传失败,请重新发表");
                        }
                    } else {
                        val msg = Message.obtain()
                        msg.what = UPLOAD_FAIL
                        msg.obj = i
                        handler.sendMessage(msg)
                        //ToastUtils.showText("图片"+uploadFile.getAbsolutePath()+"上传失败,请重新发表");
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
    }

    /**
     * 发表跟贴
     */
    private fun sendToicPost() {
        //首先判断是否有图片上传
        if (images != null && images.size > 0) {
            if (urlMap == null || urlMap.size < images.size) {
                //如果没有上传完毕则 不请求发贴
                return
            }
        }
        if (netPicList == null) {
            netPicList = ArrayList()
        }
        netPicList.clear()
        val key: Array<Any> = urlMap.keys.toTypedArray()
        Arrays.sort(key) //升序排列
        for (element in key) {
            netPicList.add(urlMap[element])
        }
        //判断是否登录
        if (!UserInforManager.getInstance().isLogin) {
            UserInforManager.getInstance().toLoginPage(this)
            return
        }
        val paramMap = ParamMap()
        paramMap.putEncode("uid", UserInforManager.getInstance().userInfor.uid)
        paramMap.putEncode("topicId", topicId)
        paramMap.putEncode("type", TypeConstant.COMMENT_PARENT)
        paramMap.putEncode("content", mSendPostContent)
        if (isAnswer) {
            paramMap.putEncode("answer", answer.toString())
        }
        paramMap.putEncode("commentId", "0") //没有帖子 传0即可
        paramMap.putEncode("toUid", "0") //没有被恢复的用户 传0即可
        paramMap.putEncode("title", mSendPostTitle) //title
        if (gid.isNotEmpty()) {
            paramMap.putEncode("gid", gid) //军团发帖
        }
        var filesStr: String? = "" //帖子连接字符集
        if (netPicList != null && netPicList.size > 0) {
            for (i in netPicList.indices) {
                if (i >= maxNumPic) {
                    //至上传三张图片
                    break
                }
                filesStr += if (i == 0) {
                    netPicList[i]
                } else {
                    "," + netPicList[i]
                }
            }
        }
        paramMap.putEncode("files", filesStr)
        HttpUtils.ParmsMapMD5(paramMap)
        val httpListener: HttpListener<DataBean<PostItemBean>> = object : HttpListener<DataBean<PostItemBean>>() {
            override fun onStart() {
                DialogUtils.getInstance().showProgressDialog(thisActivity, "正在发表中...")
            }

            override fun onError(error: VolleyError) {
                DialogUtils.getInstance().dismissProgressDialog()
                ToastUtils.showText(AppApplication.getInstance().getString(R.string.neterror))
            }

            override fun onSuccess(response: DataBean<PostItemBean>) {
                DialogUtils.getInstance().dismissProgressDialog()
                if (response.noError()) {
                    hideSoftBiaoQin()
                    val postItemBean = response.data
                    if (postItemBean != null) {
                        postItemBean.ctype = "3"
                        //ToastUtils.makeText("发表成功");
                        isSendSucces = true
                        mSendPostContent = "" //重置发表内容
                        if (isAnswer) {
                            ToastUtils.makeText(response.msg)
                            LiveEventBus.get(Config.EventBus.questionSuccess).post(true)
                        } else if (gid.isNotEmpty()) {
                            ToastUtils.makeText(response.msg)
                            LiveEventBus.get(Config.EventBus.armyTopicSuccess).post(true)
                        } else {
                            val bundle = Bundle()
                            bundle.putInt("type", 2)
                            bundle.putSerializable("post", postItemBean)
                            if (isShaidan) {
                                bundle.putBoolean("postTitle", isShaidan)
                            }
                            EventBus.getDefault().post(bundle)
                        }
                        finish()
                    } else {
//                        ToastUtils.makeText("发表失败,请重试");
                        showOkDialog()
                    }
                } else {
//                    ToastUtils.makeText(response.getMsg());
                    showOkDialog()
                }
            }
        }
        //请求网络
        HttpUtils.addPostRequest(URIContant.TOPIC_POST_LEAVEMSG_2052, object : TypeToken<DataBean<PostItemBean?>?>() {}.type, classTag, paramMap, httpListener)
    }


    /**
     * 得到图库中的图
     *
     * @param data
     * @return
     */
    private fun getImageBitmap(data: Intent) {
        //获取相册返回的数据
        //图集数据
        if (images == null) {
            images = ArrayList()
        }
        resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
        Thread(Runnable {
            for (i in resultPhotos.indices) {
                val str = resultPhotos[i]
                if (!TextUtils.isEmpty(str.path)) {
                    val sib = SendImageBean(str.path)
                    if (sib.file != null && sib.image != null) {
                        images.add(sib)
                    } else {
                        handler.sendEmptyMessage(COMPRESS_FAIL)
                        //ToastUtils.showText("找不到图片 " + str + ",请检查图片是否存在");
                    }
                } else {
                    handler.sendEmptyMessage(COMPRESS_FAIL)
                    //ToastUtils.showText("获取图片失败,请检查图片是否存在");
                }
            }
            if (images.size > 0) {
                //更新上传显示的图片的数据
//               updateUploadData();
                handler.sendEmptyMessage(RETURN_UPDATA)
            }
        }).start()
    }

    /**
     * 改变数据(从图库返回时调用)
     */
    private fun changeImageGridData() {
        if (images == null) {
            images = ArrayList()
        }
        if (images.size < maxNumPic) {
            addPic.visibility = View.VISIBLE
        } else {
            addPic.visibility = View.GONE
        }
        //刷新图片缩略图
        if (images.size in 1..maxNumPic && ll_picContainer != null) {
            ll_picContainer.removeAllViews()
            for (i in images.indices) {
                val picWithDel = PicWithDel(this, images[i].image)
                picWithDel.setOnClickListener(this)
                picWithDel.tag = images[i]
                ll_picContainer.addView(picWithDel)
            }
        }
    }


    override fun onFocusChange(v: View, hasFocus: Boolean) {
        //当exitView获取焦点时 弹出键盘 隐藏菜单
        if (hasFocus) {
            if (menu2 != null) {
                menu2.visibility = View.VISIBLE
            }
        }
    }


    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        changePostBtnColor()
    }

    /**
     * 更改发帖按钮的颜色
     */
    private fun changePostBtnColor() {
        if (tv_sendpost != null && content != null) {
            if (!TextUtils.isEmpty(content.text.toString().trim { it <= ' ' })) {
                tv_sendpost.setTextColor(resources.getColor(R.color.common_bg_green_1))
            } else {
                tv_sendpost.setTextColor(resources.getColor(R.color.send_post_btn))
            }
        }
    }

    override fun afterTextChanged(s: Editable) {}
    private fun showOkDialog() {
        if (confirmDialog == null) {
            confirmDialog = LayoutInflater.from(this).inflate(R.layout.dialog_send_post, null)
            val title = confirmDialog?.findViewById<View>(R.id.tv_title) as TextView
            title.text = AppApplication.getInstance().getString(R.string.send_post_error)
            val confirm = confirmDialog?.findViewById<View>(R.id.tv_ok) as TextView
            confirm.setOnClickListener(this)
        }
        if (dialogParams == null) {
            dialogParams = HashMap()
            dialogParams!!["local"] = Gravity.CENTER
            dialogParams!!["width"] = 280
            dialogParams!!["touchOutside"] = false
        }
        DialogUtils.getInstance().showCDialog(confirmDialog, this, dialogParams)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            if (requestCode == Config.ResultCode.resultCodePhoto) {
                getImageBitmap(data)
            }
        }
    }

    override fun onBackPressed() {
        if (mControl?.onBackPressed()!!) {
            super.onBackPressed()
            overridePendingTransition(0, R.anim.translate_slide_out_bottom)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpUtils.cancelAllRequests(classTag)
        if (isSendSucces) {
            //新建线程清空数据
            object : Thread() {
                override fun run() {
                    val ed = mSp.edit()
                    ed.putString(ConfigKeyConstant.sendArticle_content, "")
                    ed.putString(ConfigKeyConstant.sendArticle_title, "")
                    ed.putString(ConfigKeyConstant.sendArticle_images, "")
                    ed.apply()
                }
            }.start()
        } else {
            // 新建线程 保存用户数据
            object : Thread() {
                override fun run() {
                    //删除刚才新建的图片
                    var imagePathStr: String? = ""
                    if (images != null && images.size > 0) {
                        var f: File?
                        for (i in images.indices) {
                            f = images[i].file
                            imagePathStr += if (i == images.size - 1) {
                                images[i].path
                            } else {
                                images[i].path + ","
                            }
                            if (f != null && f.exists()) {
                                f.delete()
                            }
                        }
                    }
                    images.clear()
                    val content = content.text.toString().trim { it <= ' ' }
                    val title = noEmojiTitle.text.toString().trim { it <= ' ' }
                    val ed = mSp.edit()
                    ed.putString(ConfigKeyConstant.sendArticle_content, content)
                    ed.putString(ConfigKeyConstant.sendArticle_title, title)
                    ed.putString(ConfigKeyConstant.sendArticle_images, imagePathStr)
                    ed.apply()
                }
            }.start()
        }
    }
}